package com.zwz.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zwz.bean.CommentsInfo;
import com.zwz.controller.jwt.JwtConfig;
import com.zwz.controller.util.Result;
import com.zwz.service.CommentsInfoService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author Alysia
 * @createDate 2022/11/11 14:19
 * @description 评论相关控制器类
 */

@RestController
@RequestMapping("/comments")
public class CommentsController {


    @Resource
    private CommentsInfoService commentsInfoService;
    @Resource
    private JwtConfig jwtConfig;


    /**
     * 添加评论
     *
     * @param jsonObject 三个数据；公司id，用户token（用来转为用户id），评论内容
     * @return 操作结果
     */
    @PostMapping("/add")
    public Result addComments(@RequestBody JSONObject jsonObject) {
        Integer companyId = jsonObject.getInteger("companyId");
        String commentsContent = jsonObject.getString("commentsContent");
        String token = jsonObject.getString("token");
        token = token.replace("\"", "");

        CommentsInfo commentsInfo = new CommentsInfo();
        Integer userId = Integer.valueOf(jwtConfig.getUserIdFromToken(token));
        commentsInfo.setUserId(userId);
        commentsInfo.setCompanyId(companyId);
        commentsInfo.setCommentsContent(commentsContent);
        commentsInfo.setCommentsTime(new Date());

        if (commentsInfoService.save(commentsInfo)) {
            return Result.success("发布成功！");
        } else {
            return Result.error("服务器异常");
        }


    }

    /**
     * 分页查询相关
     *
     * @param currentPage 当前页码
     * @param pageSize    每页条数
     * @param companyId   公司id
     * @return 一页评论信息数据
     */
    @GetMapping("/page/{currentPage}/{pageSize}")
    public Result page(@PathVariable int currentPage, @PathVariable int pageSize, String companyId) {
        IPage<CommentsInfo> page = new Page<>(currentPage, pageSize);
        LambdaQueryWrapper<CommentsInfo> lqw = new LambdaQueryWrapper<>();
        lqw.eq(CommentsInfo::getCompanyId, companyId);
        lqw.orderByDesc(CommentsInfo::getCommentsId);
        return Result.success(commentsInfoService.page(page, lqw));
    }
}
